#!/usr/bin/env python
#
# Copyright 2015 Time My Life team (NSC 2015)
#
import webapp2
import jinja2
import os
import datetime
import numpy
import logging
from dbase import *


JINJA_ENV = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape'],
    autoescape=True)

    
class MainHandler(webapp2.RequestHandler):
    def get(self):
        self.response.write('hello, world')
        

class TestPutHandler(webapp2.RequestHandler):
    def get(self):
        ''' Test put new ID into datastore '''
        try:
            id = int(self.request.get('id'))
            new_account = Account(id=id)
            new_account.put()
            self.response.write('ok')
        except:
            self.response.write('Use http://localhost:XXXX/put?id=????')

        
class TestLatestHandler(webapp2.RequestHandler):
    def get(self):
        ''' Retrieve latest ID from datastore '''
        account_query = Account.query().order(-Account.timestamp)
        accounts = account_query.fetch(1)
        id = accounts[0].id
        logging.info('Got' + str(id))
        try:
            
            self.response.write('Last account id is %d'%id)
        except:
            self.response.write('Use http://localhost:XXXX/latest')

            
class TestQueryHandler(webapp2.RequestHandler):
    def get(self):
        ''' Test query ID from datastore '''
        try:
            id = int(self.request.get('id'))
        except:
            self.response.write('Use http://localhost:XXXX/query?id=????')
        account_query = Account.query(Account.id==id).order(-Account.timestamp)
        accounts = account_query.fetch(1)
        try:
            template_values = {'account_id':str(accounts[0].id), 'account_timestamp':str(accounts[0].timestamp)}
            template = JINJA_ENV.get_template('test_query.html')
            self.response.write(template.render(template_values))
        except:
            self.response.write('Check id value')

            
class TestPostHandler(webapp2.RequestHandler):
    def get(self):
        ''' Generate webpage for posting data '''            
        template = JINJA_ENV.get_template('test_post.html')
        self.response.write(template.render({}))
    def post(self):
        ''' Extract id and values from POST message '''
        try:
            id = int(self.request.get('id'))
            values_txt = self.request.get('values')
            values = [int(x) for x in values_txt.split(',')]  # generate list of integer numbers
            logging.info('Got %d:%s'%(id,values_txt))
        except:
            logging.debug('Wrong ID or values not in x1,x2,...,xn format')
            id = 0
        account_query = Account.query(Account.id==id)
        accounts = account_query.fetch(1)
        if len(accounts) > 0:
            now = datetime.datetime.now()                
            id_key = accounts[0].key
            new_data = DataObject(parent=id_key, timestamp=now, values=values)
            new_data.put()
            logging.debug('Datastore updated')
        else:
            logging.debug('Unknown ID')
        self.redirect('/post')

        
class TestLookupHandler(webapp2.RequestHandler):
    def get(self):
        template_values = {'id':None, 'values':None}
        try:
            id = int(self.request.get('id'))
            values_txt = self.request.get('values')
            values = [int(x) for x in values_txt.split(',')] 
            template_values = {'id':str(id), 'values':values}
        except:
            logging.debug('No ID and/or values')
        template = JINJA_ENV.get_template('test_lookup.html')
        self.response.write(template.render(template_values))
    def post(self):
        try:
            id = int(self.request.get('id'))
            logging.info('Got ID %d'%id)
        except:
            logging.debug('Something wrong with ID')
            id = 0
        account_query = Account.query(Account.id==id)
        accounts = account_query.fetch(1)
        if len(accounts) > 0:
            dataobj_query = DataObject.query(ancestor=accounts[0].key).order(-DataObject.timestamp)
            dataobjs = dataobj_query.fetch(1) # get the latest one
            logging.info('Got data object: %d'%len(dataobjs[0].values))            
            values = ','.join([str(v) for v in dataobjs[0].values])
            dest_url = '/lookup?id=%d&values=%s'%(id,values)
        else:
            logging.debug('Unknown ID')
            dest_url = '/lookup'
        self.redirect(dest_url)
        
        
app = webapp2.WSGIApplication([
    ('/', MainHandler),
    ('/put', TestPutHandler),
    ('/latest', TestLatestHandler),
    ('/query', TestQueryHandler),
    ('/post', TestPostHandler),
    ('/lookup', TestLookupHandler)
], debug=True)
